package main

import (
	vesselPb "gitee.com/whello/shippy-vessel/proto/vessel"
	pb "gitee.com/whello/shippy-consignment/proto/consignment"

	"context"
	"errors"
	"log"
	"os"

	"github.com/micro/go-micro"
	"github.com/micro/go-micro/metadata"
	"github.com/micro/go-micro/server"
)

const (
	PORT         = ":50051"
	DEFAULT_HOST = "127.0.0.1:27017"
)

func main() {
	// cmd.Execute()

	// 获取容器设置的数据库地址环境变量的值
	dbHost := os.Getenv("DB_HOST")
	if dbHost == "" {
		dbHost = DEFAULT_HOST
	}

	session, err := CreateSession(dbHost)
	// 创建于 MongoDB 的主会话，需在退出 main() 时候手动释放连接
	defer session.Close()
	if err != nil {
		log.Fatalf(" create session error: %v \n", err)
	}

	srv := micro.NewService(
		micro.Name("go.micro.srv.shippy.consignment"),
		micro.Version("latest"),
		micro.WrapHandler(AuthWrapper),
	)

	// 解析命令行参数
	srv.Init()

	vClient := vesselPb.NewVesselServiceClient(srv.Client())

	_ = pb.RegisterShippingServiceHandler(srv.Server(), &service{session, vClient})

	if err := srv.Run(); err != nil {
		log.Fatalf(" failed to serve: %v ", err)
	}


}

func AuthWrapper(fn server.HandlerFunc) server.HandlerFunc {
	return func(ctx context.Context, req server.Request, resp interface{}) error {
		if os.Getenv("DISABLE_AUTH") == "true" {
			return fn(ctx, req, resp)
		}
		meta, ok := metadata.FromContext(ctx)
		if !ok {
			return errors.New("no auth meta-data found in request")
		}

		// Note this is now uppercase (not entirely sure why this is...)
		token := meta["Token"]
		// Auth here

		// authClient := userPb.NewUser

	}
}
